<template>
  <div class="upd-cus">
    <el-dialog v-el-drag-dialog="{ drag: true, full: false, resize: true }" :visible="true" :close-on-click-modal="false"
      @close="closeMd" title="修改客户">
      <el-form :model="fm.ps" :ref="fm.fname" :label-width="'120px'" @keyup.enter.native="onSubmit">
        <el-form-item label="客户类型" prop="cusType" :rules="[
          { required: true, message: '请选择客户类型', trigger: 'change' }
        ]">
          <el-select v-model="fm.ps.cusType" clearable filterable placeholder="新客户类型选择" style="width: 100%">
            <el-option v-for="it in allCusType" :key="it.id" :label="it.typeName" :value="it.id"
              @click.native="selCusType(it)"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="客户信息" required>
          <el-col :span="8">
            <el-form-item prop="baseUserId.realName" style="margin-bottom: 0" :rules="[
              { required: true, message: '请输入客户姓名', trigger: 'blur' },
              { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
            ]">
              <el-input v-model="fm.ps.baseUserId.realName" placeholder="请输入姓名"
                @blur="fillCompany(fm.ps.baseUserId.realName)"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1" style="min-height: 10px;">&nbsp;</el-col>

          <el-col :span="15">
            <el-form-item prop="baseUserId.phone" style="margin-bottom: 0" :rules="[
              { required: true, message: '请输入客户电话', trigger: 'blur' },
              { min: 11, max: 11, message: '手机号为11位数字', trigger: 'blur' }
            ]">
              <el-input v-model="fm.ps.baseUserId.phone" placeholder="请输入手机号"
                @blur="ckCustomPhone(fm.ps.baseUserId.phone)"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>


        <el-form-item label="约定付款时间" prop="agreeOnPayDay" :rules="[
          { required: true, message: '约定付款时间不能为空' },
          { type: 'number', message: '约定付款时间为数字值' }
        ]">
          <el-input maxlength="2" style="width: 170px;" type="text" v-model.number="fm.ps.agreeOnPayDay">
            <template slot="prepend">每月</template>
            <template slot="append">号</template>
          </el-input>
        </el-form-item>

        <el-form-item label="公司名称" prop="unitName" :rules="[
          { required: true, message: '请输入公司名称', trigger: 'blur' },
          { min: 1, max: 20, message: '公司名称长度最多为20位字符', trigger: 'blur' }
        ]">
          <el-input v-model="fm.ps.unitName" placeholder="请输入公司名称（最大长度为20位）"></el-input>
        </el-form-item>

        <el-form-item label="单位简称" prop="unitSimple" :rules="[
          { required: true, message: '请输入单位简称', trigger: 'blur' },
          { min: 1, max: 16, message: '单位简称长度最多为16位字符', trigger: 'blur' }
        ]">
          <el-input v-model="fm.ps.unitSimple" placeholder="请输入单位简称"></el-input>
        </el-form-item>

        <el-form-item label="业务员" prop="serviceMan" :rules="[
          { required: true, message: '请选择业务员', trigger: 'change' }
        ]">
          <el-select v-model="fm.ps.serviceMan" clearable filterable placeholder="请选择业务员" style="width: 100%">
            <el-option v-for="it in allSalesman" :key="it.baseUserId.uname" :label="it.baseUserId.realName"
              :value="it.baseUserId.realName + '-' + it.baseUserId.uname">
              <span>{{ it.baseUserId.realName }}</span>
              <span>{{ it.baseUserId.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="职务" prop="cusRole" :rules="[
          { required: false, message: '请输入职务名称', trigger: 'blur' },
          { min: 1, max: 20, message: '职务名称长度最多为20位字符', trigger: 'blur' }
        ]">
          <el-input v-model="fm.ps.cusRole" placeholder="请输入职务名称"></el-input>
        </el-form-item>

        <template v-if="fm.isShowGk == 1">
          <el-form-item label="是否挂靠" prop="isDepend" :rules="[
            { required: true, message: '请选择是否挂靠', trigger: 'blur' }
          ]">
            <el-radio-group v-model="fm.ps.isDepend">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>

        <template v-if="fm.ps.isDepend == 1">
          <el-form-item label="上网费费率" prop="onlineRatio" :rules="[
            { required: false, message: '请输入上网费费率', trigger: 'blur' },
            this.$rules.isFloat()
          ]">
            <el-input v-model.number="fm.ps.onlineRatio" placeholder="上网费费率 如：50=50%"><span
                slot="suffix">%</span></el-input>
          </el-form-item>

          <el-form-item label="开发票费率" prop="invoiceRatio" :rules="[
            { required: false, message: '请输入开发票费率', trigger: 'blur' },
            this.$rules.isFloat()
          ]">
            <el-input v-model.number="fm.ps.invoiceRatio" placeholder="开发票费率 如：50=50%"><span
                slot="suffix">%</span></el-input>
          </el-form-item>

          <el-form-item label="营业执照" prop="businessNum" :rules="[
            { min: 1, max: 36, message: '营业执照编号长度最多为16位字符', trigger: 'blur' }
          ]">
            <el-input v-model="fm.ps.businessNum" placeholder="请输入营业执照编号"></el-input>
          </el-form-item>

          <el-form-item label="身份证号码" prop="idCard" :rules="[
            { validator: valIdCard, trigger: ['blur', 'change'] }
          ]">
            <el-input v-model="fm.ps.idCard" placeholder="请输入身份证号码"></el-input>
          </el-form-item>

          <el-form-item label="身份证照片">
            <el-col :span="11">
              <el-form-item prop="idCardFrontImg" style="margin-bottom: 0" :rules="[
                { required: false, message: '请上传身份证人像面照片', trigger: 'change' }
              ]">
                <UploadImg :imgName="'idCardFrontImg'" @getImgUrl="setImgUrl" :url="'/company/upload'"
                  :ps="{ userName: uname }" :src="fileBaseUrl + fm.ps.idCardFrontImg" :tiptext="'（人像面）'" />
              </el-form-item>
            </el-col>
            <el-col :span="2" style="min-height: 10px;">&nbsp;</el-col>
            <el-col :span="11">
              <el-form-item prop="idCardBackImg" style="margin-bottom: 0" :rules="[
                { required: false, message: '请上传身份证国徽面照片', trigger: 'change' }
              ]">
                <UploadImg :imgName="'idCardBackImg'" @getImgUrl="setImgUrl" :url="'/company/upload'"
                  :ps="{ userName: uname }" :src="fileBaseUrl + fm.ps.idCardBackImg" :tiptext="'（国徽面）'" />
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item label="服务内容" prop="serviceContent" :rules="[
            { min: 1, max: 200, message: '服务内容长度最多为200个字符串', trigger: 'blur' }
          ]">
            <el-input type="textarea" :autosize="{ minRows: 5, maxRows: 4 }"
              placeholder="请输入服务内容，必须尽量填写清楚供应商的服务内容和产品(200字内)" maxlength="200" v-model="fm.ps.serviceContent">
            </el-input>
          </el-form-item>
        </template>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit" :disabled="fm.sb.load">{{ fm.sb.text }}</el-button>
        <el-button @click="resetForm">重置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import elDragDialog from '@/directive/el-drag-dialog';
import UploadImg from '@/components/UploadImg';

import * as cusService from '@/api/services/cus.service';
import * as commonService from '@/api/services/common.service';

export default {
  name: 'UpdCus',
  directives: { elDragDialog },
  props: { myData: Object },
  components: { UploadImg },
  computed: {
    ...mapGetters(['lunitNum', 'uname'])
  },
  data() {
    return {
      // 文件地址前缀
      fileBaseUrl: this.C.fileBaseUrl,

      obj: this.myData.obj,
      fm: {
        fname: 'updCusFm',
        sb: { load: false, text: '立即修改' },
        isShowGk: 0, // 是否显示挂靠项
        ps: {
          agreeOnPayDay: 15,
          id: '',
          cusType: '',
          baseUserId: {
            phone: '',
            realName: ''
          },
          unitName: '',
          cusRole: '',
          // 是否挂靠 默认：否
          isDepend: '0',
          // 上网费费率
          onlineRatio: '',
          // 开发票费率
          invoiceRatio: '',
          serviceMan: '',
          unitSimple: '',
          businessNum: '',
          idCard: '',
          idCardFrontImg: '',
          idCardBackImg: '',
          serviceContent: '',
          addTime: '',
        },
      },
      /*-----自定义表单验证--begin----*/

      /** 验证-身份证号码 */
      valIdCard: (rule, value, callback) => {
        if (value && value !== '' && !this.FV.isIdCard(value)) {
          callback(new Error(this.FV.ERROR_ID_CARD));
        } else {
          callback();
        }
      },
      /*-----自定义表单验证--end------*/

      allCusType: [],
      allSalesman: [],

    }
  },
  created() {
    const that = this, o = that.obj;

    that.getCompanyAllCusType();
    that.getCompanyAllSalesman();
    // that.getCompanyCusById();

    /*******初始化-数据**********/
    if (o) {
      that.fm.ps = {
        id: o.id,
        cusType: o.cusTypeId ? o.cusTypeId.id : '',
        baseUserId: {
          // 添加/修改需要
          uname: o.baseUserId.uname,
          phone: o.baseUserId.phone,
          realName: o.baseUserId.realName
        },
        unitName: o.unitName,
        agreeOnPayDay: o.agreeOnPayDay,
        addTime: o.addTime,
        cusRole: o.cusRole,
        // 是否挂靠 默认：否
        isDepend: o.isDepend + '',
        // 上网费费率
        onlineRatio: o.onlineRatio,
        // 开发票费率
        invoiceRatio: o.invoiceRatio,
        serviceMan: o.serviceMan,
        unitSimple: o.unitSimple,
        businessNum: o.businessNum,
        idCard: o.idCard,
        idCardFrontImg: o.idCardFrontImg,
        idCardBackImg: o.idCardBackImg,
        serviceContent: o.serviceContent,
        dutyService: o.dutyService,
      };
    }
  },
  methods: {
    /* 关闭弹框 */
    closeMd() {
      this.$emit('myClick', { state: false });
    },
    /**
     * 获取-单位所有客户类型
     */
    getCompanyAllCusType() {
      const that = this;

      let loading = that.U.qloading('数据请求中...');
      commonService.getCompanyAllCusType({}).then(res => {
        that.allCusType = res.cusTypes;

        that.U.qclose(loading);
      });
    },
    /**
     * 获取-单位所有业务员(只要业务部的)
     */
    getCompanyAllSalesman() {
      const that = this;

      let loading = that.U.qloading('数据请求中...');
      cusService.getCompanyAllSalesman({ deptName: "业务部", staffState: "NORMAL,TRY" }).then(res => {
        that.allSalesman = res.data;

        that.U.qclose(loading);
      });
    },

    /**
     * 获取-客户信息
     */
    getCompanyCusById() {
      const that = this;

      let loading = that.U.qloading('数据请求中...');
      let o = that.obj;
      cusService.getCompanyCusById({ id: o.id }).then(res => {
        let result = res.data;
        that.fm.ps = {
          cusType: result.cusTypeId.id,
          unitName: result.unitName,
          cusRole: result.cusRole,
          isDepend: result.isDepend + '', // 是否挂靠 默认：是
          serviceMan: result.serviceMan,
          unitSimple: result.unitSimple,
          businessNum: result.businessNum,
          idCard: result.idCard,
          addTime: result.addTime,
          agreeOnPayDay: result.agreeOnPayDay,
          idCardFrontImg: result.idCardFrontImg,
          idCardBackImg: result.idCardBackImg,
          serviceContent: result.serviceContent,
          baseUserId: {
            phone: result.baseUserId.phone,
            realName: result.baseUserId.realName
          },
          id: result.id
        };

        if (result.cusTypeId.isSupplier === 0) {
          that.fm.ps.isDepend = '0';
          that.fm.ps.unitSimple = "";
          that.fm.ps.businessNum = "";
          that.fm.ps.idCard = "";
          that.fm.ps.serviceContent = "";
          that.fm.ps.idCardBackImg = "";
        } else {
        }
        let editBaseUserId = {
          phone: that.fm.ps.baseUserId.phone,
          realName: that.fm.ps.baseUserId.realName,
          id: result.baseUserId.id,
          uname: result.baseUserId.uname || null,
          regWay: result.baseUserId.regWay || null,
          ustate: result.baseUserId.ustate || null,
          nickName: result.baseUserId.nickName || null,
          headImg: result.baseUserId.headImg || null,
          atime: result.baseUserId.atime || null,
        }
        that.fm.ps.baseUserId = editBaseUserId;
        that.fm.ps.id = result.id;
        that.fm.ps.addTime = result.addTime;
        that.fm.ps.address = result.address;
        that.fm.ps.addressLonlat = result.addressLonlat;
        that.fm.ps.isDel = result.isDel;
        that.fm.ps.dutyService = result.dutyService || null;
        that.fm.ps.personInCharge = result.personInCharge || null;
        that.U.qclose(loading);
      });
    },
    /**
     * 选择-客户类型
     * @param o 客户类型对象
     */
    selCusType(o) {
      const that = this;

      that.fm.isShowGk = (o.typeName == '运输公司') ? 1 : 0;
    },
    /**
     * 设置-图片url
     * @param e 上传成功后的服务器图片url
     */
    setImgUrl(e) {
      this.fm.ps[e.name] = e.url;

      if (e.url) {
        this.clearFileValText(e.name);
      } else {
        this.$refs[this.fm.fname].validateField(e.name);
      }
    },
    /**
     * 提交表单
     */
    onSubmit() {
      const that = this, U = that.U, fm = that.fm, ps = U.scopy(fm.ps), sb = that.fm.sb;
      if (that.fm.ps.agreeOnPayDay > 28 || that.fm.ps.agreeOnPayDay < 0) {
        console.log(that.fm.ps.agreeOnPayDay)
        return alert('约定付款时间请输入1-28之间的数字')
      }
      that.$refs[that.fm.fname].validate((valid) => {
        if (!valid) {
          return U.qerror('验证不通过');
        } else {
          sb.load = true;

          // 添加固定参数
          ps.unitNum = that.lunitNum;
          ps.cusType = (ps.cusType).toString();
          ps.recomMan = ps.serviceMan;
          cusService.adupCompanyCus(ps, 'update').then(res => {
            sb.load = false;

            if (!res || res.code != 1) {
              U.qerror(res.msg);
            } else {
              U.qsuccess(res.msg);

              // 关闭弹框
              that.closeMd();

              // 调用父组件方法-重新加载数据
              that.$emit('reloadDg');
            }

          });
        }
      });
    },
    resetForm() { // 重置表单
      this.$refs[this.fm.fname].resetFields();
    },
    /**
     * 清除某个字段的验证信息
     * @param filed 字段名
     */
    clearFileValText(filed) {
      /*当然，你可以打印一下fields*/
      let _field = this.$refs[this.fm.fname].fields
      _field.map(i => {
        // 通过prop属性值相同来判断是哪个输入框，比如：要移除prop为'user'
        if (i.prop === filed) {
          // 清除验证信息
          i.clearValidate();

          return false;
        }
      });
    },
    /**
     * 输入姓名自动默认公司名称
     * @param name
     */
    fillCompany(name) {
      let that = this;

      if (that.fm.ps.baseUserId.realName) {
        that.fm.ps.unitName = that.fm.ps.baseUserId.realName + "的公司";

        that.fm.ps.unitSimple = that.fm.ps.baseUserId.realName;
      }
    },
    /**
     * 验证客户电话是否重复
     * @param phone
     */
    ckCustomPhone(phone) {
      ckCustomPhone({ phone: phone }).then(res => {
        if (res.code === 1) {
          fm.sb.load = true;
        } else {
          fm.sb.load = false;
        }
      });
    }
  },
}
</script>
